package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class CheckLoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        //0. 禁止远程访问
        /*String remoteAddr = request.getRemoteAddr();
        System.out.println(remoteAddr);
        if (!remoteAddr.equals("0:0:0:0:0:0:0:1")) {
            return;
        }*/
        //获取本次请求的URI
        String requestURI = request.getRequestURI();

        String[] urls = {
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/user/sendMsg",
                "/user/login"
        };
       boolean flag= check(urls,requestURI);
       if(flag){
           //放行资源
           filterChain.doFilter(request,response);
        return;//必须加return
       }

       //2,判断用户是否登录
        //从session中查看有没有id
        Long empId =(Long) request.getSession().getAttribute("employee");
       if(empId!=null){
           BaseContext.setCurrentId(empId);
           //用户已登录，放行
           filterChain.doFilter(request,response);
           return;

        }
        //增加判断移动端登录状态，如果已登录，则直接放行
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null) {
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }


       //3,用户未登录，响应code=0 && msg=NOTLOGIN
        //json转java对象
        String jsonString = JSON.toJSONString(R.error("NOTLOGIN"));
       response.getWriter().write(jsonString);

    }

    private boolean check(String[] urls, String requestURI) {
        //路径匹配器
        AntPathMatcher pathMatcher =new AntPathMatcher();
        //遍历数组中的表达式
        for (String url : urls) {
            boolean match = pathMatcher.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }



}
